﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    public class QuickTaskWebPart : WebPart
    {
        private SPGridView grid;
        private SPDataSource datasource;
        private UserControl scriptcontrolpage;

        protected ToolBarButton checkAllTasksToolBarButton;
        protected ToolBar webPartToolBar;

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Select TaskList"), WebDescription("Select TaskList")]
        public string taskList { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Select SharePoint Group"), WebDescription("Select SharePoint Group for adding tasks")]
        public string sharepointGroup { get; set; }

        protected override void CreateChildControls()
        {
            SPWeb currentWeb = SPContext.Current.Web;

            this.TitleUrl = SPContext.Current.Web.Url + "/Lists/" + taskList;

            //Adding the .ascx with all the javascript and the hidden input form
            scriptcontrolpage = (UserControl)Page.LoadControl("/_layouts/zevenseas/controltemplates/hiddeninputsection.ascx");
            scriptcontrolpage.ID = "scriptcontrolpage";
            this.Controls.Add(scriptcontrolpage);

            //Defining a button to validate a set of documents
            checkAllTasksToolBarButton = (ToolBarButton)Page.LoadControl("/_controltemplates/ToolBarButton.ascx");
            checkAllTasksToolBarButton.Click += new EventHandler(checkAllTasksToolBarButton_Click);

            checkAllTasksToolBarButton.Text = "Complete selected tasks";
            checkAllTasksToolBarButton.ImageUrl = "/_layouts/images/CheckNames.gif";

            //Creating the toolbar and adding the button           
            webPartToolBar = (ToolBar)Page.LoadControl("/_controltemplates/ToolBar.ascx");
            webPartToolBar.Buttons.Controls.Add(checkAllTasksToolBarButton);

            this.Controls.Add(webPartToolBar);

            datasource = new SPDataSource();
            datasource.DataSourceMode = SPDataSourceMode.List;
            datasource.UseInternalName = true;
            datasource.SelectCommand = "<Query><Where><Neq><FieldRef Name=\"Status\" /><Value Type=\"Text\">Completed</Value></Neq></Where><OrderBy><FieldRef Name=\"ID\" /></OrderBy></Query>";

            try
            {
                //Defining and building the SPGrid to display the datasource
                grid = new SPGridView();
                grid.AutoGenerateColumns = false;

                //CheckBox
                BoundField checkbox = new BoundField();
                checkbox.DataField = "Id";
                checkbox.DataFormatString = "<input type='checkbox' group='siteCheckboxes' name='{0}' onclick='checkBoxClick();'>";
                checkbox.HtmlEncode = false;
                checkbox.HeaderText = "<input type='checkbox' id='selectAllCheckBox' onclick='selectAllCheckBoxClick(this);' />";
                grid.Columns.Add(checkbox);

                //Title menu with ECB
                SPMenuField titleMenu = new SPMenuField();
                titleMenu.HeaderText = "Title";
                titleMenu.TextFields = "Title";
                titleMenu.MenuTemplateId = "TaskListMenu";

                titleMenu.TokenNameAndValueFields = "EDIT=ID";
                titleMenu.SortExpression = "Title";

                MenuTemplate itemListMenu = new MenuTemplate();
                itemListMenu.ID = "TaskListMenu";

                MenuItemTemplate editItemMenu = new MenuItemTemplate("Edit Item", "/_layouts/images/edititem.gif");
                editItemMenu.ClientOnClickNavigateUrl = SPContext.Current.Web.Url + "/Lists/" + 
                    taskList + "/editform.aspx?id=%EDIT%&Source=" + SPContext.Current.Web.Url;
                itemListMenu.Controls.Add(editItemMenu);

                SubMenuTemplate listSettings = new SubMenuTemplate();
                listSettings.Text = "Assign Task to";
                listSettings.Description = "Quickly assing this task to an user";
                listSettings.ImageUrl = "/_layouts/images/ALLUSR.gif";
                                
                foreach (SPUser user in SPContext.Current.Web.Users)
                {
                    MenuItemTemplate listItem = new MenuItemTemplate();
                    listItem.Text = user.Name.ToString();
                    listItem.Description = string.Format("Assign to task to {0}", user.Name);

                    string url = string.Format("{0}/_layouts/zevenseas/taskassign.aspx?List={1}&Item=%EDIT%&UserId={2}&source={3}", 
                        SPContext.Current.Web.Url, taskList, user.ID.ToString(), SPContext.Current.Web.Url);
                    listItem.ClientOnClickNavigateUrl = url;
                    listSettings.Controls.Add(listItem);
                }

                itemListMenu.Controls.Add(listSettings);
                this.Controls.Add(itemListMenu);

                grid.Columns.Add(titleMenu);

                //Status column
                SPBoundField status = new SPBoundField();
                status.DataField = "Status";
                status.HeaderText = "Status";
                grid.Columns.Add(status);

                //AssignedTo Column
                zsBoundUserField assigned = new zsBoundUserField();
                assigned.DataField = "AssignedTo";
                assigned.HeaderText = "Assigned To";
                grid.Columns.Add(assigned);

                this.Controls.Add(grid);
            }
            catch (Exception error)
            {
                SPUtility.TransferToErrorPage(error.Message.ToString());
            }

            if (!Page.IsPostBack)
            {
                DataBind(taskList);
            }

            base.CreateChildControls();

        }

        void DataBind(string listName)
        {
            if (!string.IsNullOrEmpty(listName))
            {
                datasource.List = SPContext.Current.Web.Lists[listName];
                try
                {
                    grid.DataSource = datasource;
                    grid.DataBind();
                }
                catch (Exception error)
                {
                    Literal literal = new Literal();
                    literal.Text = error.Message.ToString();
                    this.Controls.Add(literal);
                }
            }
        }

        void checkAllTasksToolBarButton_Click(object sender, EventArgs e)
        {
            //Getting a reference to the hiddenInput field to get the values
            string controlId = "ctl00" + "$" + this.Parent.ID + "$" + this.ID + "$scriptcontrolpage" + "$HiddenSiteSelections";
            System.Web.UI.HtmlControls.HtmlInputHidden inputsection = (System.Web.UI.HtmlControls.HtmlInputHidden)this.Page.FindControl(controlId);

            if (inputsection != null)
            {
                string[] ids = inputsection.Value.Split(new Char[] { '#' });
                SPList list = SPContext.Current.Web.Lists[taskList];

                foreach (string id in ids)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        SPListItem item = list.GetItemById(Convert.ToInt32(id));
                        item["PercentComplete"] = 1;
                        item["Status"] = "Completed";
                        item.SystemUpdate();
                    }
                }
            }

            DataBind(taskList);
        }
    
    }
}
